package util;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class ParamEncryptionUtils {
    /**
     * 鍙傛暟閬靛惊Unicode鐮佷粠灏忓埌澶ф帓搴�
     *
     * @param paramap     瑕佹帓搴忕殑Map瀵硅薄
     * @param doUrlEncode 鏄惁闇�瑕乁RLENCODE
     * @param keyToLower  鏄惁闇�瑕佸皢Key杞崲涓哄叏灏忓啓
     *                    true:key杞寲鎴愬皬鍐欙紝false:涓嶈浆鍖�
     * @return
     */
    public static String sortParam(Map<String, String> paramap, boolean doUrlEncode, boolean keyToLower) {
        String result;
        Map<String, String> tmpMap = paramap; 
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
            // 瀵规墍鏈変紶鍏ュ弬鏁版寜鐓у瓧娈靛悕鐨� ASCII 鐮佷粠灏忓埌澶ф帓搴忥紙瀛楀吀搴忥級
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 鏋勯�燯RL 閿�煎鐨勬牸寮�
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (StringUtils.isNotBlank(item.getKey())) {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (doUrlEncode) {
                        val = URLEncoder.encode(val, "utf-8");
                    }
                    if (keyToLower) {
                        buf.append(key.toLowerCase() + "=" + val);
                    } else {
                        buf.append(key + "=" + val);
                    }
                    buf.append("&");
                }
            }
            result = buf.toString();
            if (!result.isEmpty()) {
                result = result.substring(0, result.length() - 1);
            }
        } catch (Exception e) {
            return null;
        }
        return result;
    }


    // 鍘熸枃杞鍚�
    public static String convert2HmacString(byte[] data, byte[] key) {
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);
            return byte2hex(mac.doFinal(data));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    public static boolean verify(String data, String signed_data, String key) throws UnsupportedEncodingException {
        String sign = convert2HmacString(data.getBytes("utf-8"), key.getBytes("utf-8"));
        if (signed_data.equalsIgnoreCase(sign)) {
            return true;
        }
        return false;
    }
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    	byte[] data="中".getBytes("UTF-8");
    	byte[] key="XAFzdfzUCYvBNSr0xyTkZjmbd3JiXunk".getBytes("UTF-8");
    	 SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA256");
         Mac mac = Mac.getInstance("HmacSHA256");
         mac.init(signingKey);
         System.out.println(byte2hex(mac.doFinal(data)));
	}

}
